import type { FC } from 'react';
import { Button, Form, } from 'antd';
import { useMemoizedFn } from 'ahooks';
import { ArrowUpOutlined } from '@ant-design/icons';
import styles from './styles.module.less';

type ChatSenderProps = {
  loading: boolean;
  onSend?: (text: string) => void;
}

const ChatSender: FC<ChatSenderProps> = (props) => {
  const { loading } = props;
  const [form] = Form.useForm();

  const onSubmit = useMemoizedFn(() => {
    if (loading) return;
    const text = form.getFieldValue('text');
    form.resetFields();
    props.onSend?.(text);
  });

  return (
    <Form
      form={form}
      onFinish={onSubmit}
      className={styles.chat_sender}
    >
      <div className={styles.chat_input}>
        <Form.Item name="text" noStyle>
          <input type="text" placeholder="Ask me whatever you want to know..." />
        </Form.Item>
        <Form.Item shouldUpdate noStyle>
          {form => {
            const val = form.getFieldValue('text');
            return (
              <Button
                type="primary"
                disabled={!val}
                htmlType="submit"
                loading={loading}
                className={styles.send_btn}
                icon={<ArrowUpOutlined />}
              />
            );
          }}
        </Form.Item>
      </div>
    </Form>
  );
}

export default ChatSender;